//
//  B_GoodsListVC.m
//  DreamOf
//
//  Created by 薛小刚 on 2018/9/1.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_GoodsListVC.h"
#import "B_TwoButtonFooterView.h"
#import "B_GoodsListTVC.h"
#import "B_SubmitFooterView.h"
#import "B_AddGoodsVC.h"
#import "B_GoodsListModel.h"
#import "B_GoodsDetailVC.h"

@interface B_GoodsListVC ()
/// 是否是批量管理界面
@property (nonatomic, assign) BOOL isManager;

@property (nonatomic, strong) BaseTableView * mainView;

@property (nonatomic, strong) B_TwoButtonFooterView * footerView;

@property (nonatomic, strong) B_SubmitFooterView * footerView1;

@end

@implementation B_GoodsListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view = self.mainView;
    [self addFooter];
    _isManager = NO;
    [self getData:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadGoodsListData) name:@"reloadGoodsListData" object:nil];
}

- (void) reloadGoodsListData {
    [self getData:YES];
}

- (BaseTableView *)mainView {
    if (!_mainView) {
        WeakSelf(weSelf, self);
        _mainView = [[BaseTableView alloc] init];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_GoodsListTVC" bundle:nil] forCellReuseIdentifier:@"B_GoodsListTVC"];
        _mainView.numberOfRowsBlock = ^NSInteger(UITableView *tableView, NSInteger section) {
            return weSelf.dataArray.count;
        };
        _mainView.heightForRowBlock = ^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return 130;
        };
        _mainView.numberOfSectionsBlock = ^NSInteger(UITableView *tableView) {
            return 1;
        };
        _mainView.cellForRowBlock = ^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            B_GoodsListModel * model = weSelf.dataArray[indexPath.row];
            B_GoodsListTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_GoodsListTVC" forIndexPath:indexPath];
            if (weSelf.isManager) {
                cell.B_selectView.hidden = NO;
                cell.B_statusLabel.hidden = YES;
                cell.B_seleceButton.selected = model.isSelected;
                cell.B_goodsListCellSelect = ^(UIButton *btn) {
                    btn.selected = !btn.isSelected;
                    model.isSelected = btn.isSelected;
                    /// TODO:执行选中的操作
                };
            } else {
                cell.B_selectView.hidden = YES;
                cell.B_salesLabel.hidden = NO;
                cell.B_statusLabel.text = [model getGoodsStatus:model.goodsStatus];
            }
            cell.B_goodsTitle.text = model.goodsName;
            [cell.B_imageView sd_setImageWithURL:[NSURL URLWithString:model.goodsImg]];
            cell.B_priceLabel.text = [NSString stringWithFormat:@"¥%@", model.goodsPrice];
            cell.B_repertoryLabel.text = [NSString stringWithFormat:@"库存%@", model.goodsStock];
            cell.B_salesLabel.text = [NSString stringWithFormat:@"销量%@", model.goodsSalesVolume];
            
            return cell;
        };
        _mainView.didSelectRow = ^(UITableView *tableView, NSIndexPath *indexPath) {
            B_GoodsListModel * model = weSelf.dataArray[indexPath.row];
            B_GoodsDetailVC * vc = [[B_GoodsDetailVC alloc] init];
            vc.B_GoodsId = model.id;
            
            [weSelf pushNextViewController:vc];
            
        };
        
        
        [_mainView setTableViewFooterFresh:^{
            [weSelf getData:NO];
        }];
        [_mainView setTableViewHeaderFresh:^{
            [weSelf getData:YES];
        }];;
    }
    return _mainView;
}


/**
 TODO:两个按钮的底部view

 @return 返回view
 */
- (B_TwoButtonFooterView *)footerView {
    if (!_footerView) {
        WeakSelf(weSelf, self);
        _footerView = [B_TwoButtonFooterView initB_TwoButtonFooterView];
        _footerView.B_TwoButtonAction = ^(UIButton *btn) {
            if ([btn.titleLabel.text isEqualToString:@"添加商品"]) {
                B_AddGoodsVC * addGoods = [[B_AddGoodsVC alloc] init];
                
                [weSelf pushNextViewController:addGoods];
            } else if ([btn.titleLabel.text isEqualToString:@"批量管理"]) {
                weSelf.isManager = YES;
                [weSelf addFooter];
                [weSelf.mainView.tableView reloadData];
            }
            HXLog(@"Btn.titleLabel.text is %@", btn.titleLabel.text);
        };
    }
    return _footerView;
}
/**
 TODO:单个按钮的底部view
 
 @return 返回view
 */
- (B_SubmitFooterView *)footerView1 {
    if (!_footerView1) {
        WeakSelf(weSelf, self);
        _footerView1 = [B_SubmitFooterView initB_SubmitFooterView];
        [_footerView1.B_SubmitButton setTitle:@"删除" forState:UIControlStateNormal];
        _footerView1.backgroundColor = [UIColor color_pink];
        _footerView1.B_SubmitButton.backgroundColor = [UIColor color_pink];
        _footerView1.submitAction = ^{
            //TODO:执行删除
            
            [weSelf deleteGoods];
            
            
        };
    }
    return _footerView1;
}

/**
 TODO:添加底部按钮
 */
- (void) addFooter {
    CGFloat bottom = SCREEN_HEIGHT > 800 ? (50 + 24) : 50;
    if (self.isManager) {
        [self.footerView removeFromSuperview];
        [_mainView addSubview:self.footerView1];
        [self.footerView1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mainView.mas_left);
            make.right.equalTo(self.mainView.mas_right);
            make.bottom.equalTo(self.mainView.mas_bottom);
            make.height.equalTo(@(bottom));
        }];
    } else {
        [self.footerView1 removeFromSuperview];
        [_mainView addSubview:self.footerView];
        [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mainView.mas_left);
            make.right.equalTo(self.mainView.mas_right);
            make.bottom.equalTo(self.mainView.mas_bottom);
            make.height.equalTo(@(bottom));
        }];
    }
    [_mainView setTableViewFrameWithTop:5 left:0 right:0 bottom:-bottom];
}


/**
 TODO:获取网络数据

 @param isRefresh 是否是刷新
 */
- (void) getData:(BOOL) isRefresh {
    if (isRefresh) {
        self.index = 1;
    } else {
        self.index ++;
    }
    WeakSelf(weSelf, self);
    [NetworkingManager getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/yearnfor/inter/goods/selectGoodsManagerList/%@/%ld/10", getUserId(), self.index] parameters:nil isCache:isRefresh succeed:^(id data) {
        [weSelf.mainView endRefresh];
        if ([data[@"code"] isEqualToString:@"20010"]) {
            if (isRefresh) {
                [weSelf.dataArray removeAllObjects];
            }
            for (NSDictionary * dictionary in data[@"values"]) {
                B_GoodsListModel * model = [B_GoodsListModel mj_objectWithKeyValues:dictionary];
                model.isSelected = NO;
                [weSelf.dataArray addObject:model];
            }
            [weSelf.mainView.tableView reloadData];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [weSelf.mainView endRefresh];
        [KeyWindow makeToast:@"服务器异常"];
    }];
}

/**
 TODO:批量删除商品
 */
- (void)deleteGoods {
    NSMutableArray * array = [NSMutableArray array];
    for (B_GoodsListModel * model in self.dataArray) {
        if (model.isSelected) {
            [array addObject:model.id];
        }
    }
    WeakSelf(weSelf, self);
    [NetworkingManager getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/yearnfor/inter/goods/deleteGoods?str=%@", [@{@"goodsIds":array} mj_JSONString]] parameters:nil isCache:NO succeed:^(id data) {
        if ([data[@"code"] isEqualToString:@"20007"]) {
            [KeyWindow makeToast:@"删除成功"];
            [weSelf getData:YES];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
//
//    [NetworkingManager postNetworkRequestWithUrlString:@"/yearnfor/inter/goods/deleteGoods" parameters:@{@"str" : [{@"goodsIds":array} mj_JSONString]} isCache:NO succeed:^(id data) {
//        if ([data[@"code"] isEqualToString:@"20007"]) {
//            [KeyWindow makeToast:@"删除成功"];
//            [weSelf getData:YES];
//        } else {
//            [KeyWindow makeToast:data[@"message"]];
//        }
//    } fail:^(NSError *error) {
//        [KeyWindow makeToast:@"服务器异常"];
//    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
